const fs = require('fs');
const path = require('path');
const xlsx = require('xlsx');

// 读取目录下的所有.xlsx文件
const directoryPath = './excels';  // 请替换为你的目录路径
const files = fs.readdirSync(directoryPath).filter(file => file.endsWith('.xlsx'));
const outPath = './ts'; // 请替换为你的输出目录路径
const headerLine = 3;

files.forEach(file => {
    const workbook = xlsx.readFile(path.join(directoryPath, file));
    workbook.SheetNames.forEach(sheetName => {
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 });

        if (jsonData.length > 1) {
            const fieldNames = jsonData[headerLine - 3];
            const types = jsonData[headerLine - 2];
            const headers = jsonData[headerLine - 1];
            const data = jsonData.slice(1);
            let classContent = `export class ${sheetName} {\n`;
            let colLine = 0;
            headers.forEach(header => {
                let fieldName = fieldNames[colLine];
                let type = types[colLine];
                classContent += `  ${header}: ${type};\t // ${fieldName}\n`;
                colLine++;
            });

            classContent += `\n  constructor(data: { ${headers.map(header => `${header}`).join('; ')} }) {\n`;

            headers.forEach(header => {
                classContent += `    this.${header} = data.${header};\n`;
            });

            classContent += '  }\n';
            classContent += '}\n';

            // 生成Map对象
            classContent += `\nconst ${sheetName}Map: Map<number, ${sheetName}> = new Map();\n`;

            let rowLine = 0;
            data.forEach(row => {
                rowLine++;
                if (rowLine < headerLine) {
                    return;
                }
                classContent += `{\n  const obj = new ${sheetName}({\n`;
                headers.forEach((header, i) => {
                    classContent += `    ${header}: ${JSON.stringify(row[i])},\n`;
                });
                classContent += '  });\n';
                classContent += `  ${sheetName}Map.set(obj.id, obj);\n}\n`;
            });

            // 导出Map
            classContent += `\nexport { ${sheetName}Map };\n`;

            fs.writeFileSync(path.join(outPath, `${sheetName}.ts`), classContent, 'utf8');
        }
    });
});
